<?php
/**
 * 邮件队列处理 (该脚本需要挂起在Linux后台服务中运行)
 *
 * 命令：
 * bash$ ./cli email
 *
 * @author     Akon(番茄红了) <aultoale@gmail.com>
 */
class CLI_Email extends CLI
{

    public function main()
    {
        $config = Kohana::config('mail');

        Vendor::register_autoloader('Zend');

        // 进入进程循环
        while (true)
        {
            $rows = DB::select()
                ->from('mail_list')
                ->where('send_result', '=', 0)
                ->where('task_time', '<=', time())
                ->order_by('task_time', 'DESC')
                ->order_by('mail_id', 'ASC')
                ->limit($config->task['quantity'])
                ->fetch_all();

            if (empty($rows))
            {
                CLI::output('.');
                sleep(60); // 休息 60 秒钟
                continue;
            }

            // 实例化邮件发送器
            $transport = new Zend_Mail_Transport_Smtp($config->host, $config->options);

            foreach ($rows as $row)
            {
                // 邮件状态
                $set = array(
                    'send_time' => time(),
                    'send_result' => 1,
                );

                // 日志数据
                $data = array(
                    'mail_id' => $row['mail_id'],
                    'send_time' => time(),
                    'send_result' => 1,
                );

                try
                {
                    // 实例化 Zend_Mail
                    $zendMail = new Zend_Mail($config->charset);
                    $zendMail->setDefaultFrom($config->from['mail'], $config->from['name']);

                    // 发送邮件
                    $zendMail->addTo($row['to_mail'], $row['to_name'])
                        ->setFrom($row['from_mail'], $row['from_name'])
                        ->setSubject($row['subject'])
                        ->setBodyHtml($row['content'])
                        ->send($transport);

                    CLI::output("id: ".$row['mail_id']." 发送成功 <".$row['to_mail']."> √ \n");

                }
                catch (Exception $e)
                {
                    $set['send_result'] = 2;
                    $data['send_result'] = 0;
                    $data['error_msg'] = $e->getMessage();

                    CLI::output("id: ".$row['mail_id']." 发送失败 <".$row['to_mail']."> × \n");
                }

                // 更新邮件状态
                DB::update('mail_list')
                    ->set($set)
                    ->where('mail_id', '=', $row['mail_id'])
                    ->execute();

                // 写入日志
                DB::insert('mail_logs', array_keys($data))
                    ->values(array_values($data))
                    ->execute();

                sleep(1);
            }

            unset($rows, $row, $zendMail, $set, $data);

            sleep($config->task['interval']); // 休息，暂停
        }
    }

}